#include <sw/redis++/redis++.h>
#include <iostream>
#include <string>

using namespace sw::redis;

int main() {
    try {
        // 创建 Redis 连接
        ConnectionOptions connection_options;
        connection_options.host = "127.0.0.1";
        connection_options.port = 6379;
        
        Redis redis(connection_options);
        
        // 创建订阅者
        auto subscriber = redis.subscriber();
        
        // 设置消息回调函数
        subscriber.on_message([](const std::string &channel, const std::string &message) {
            std::cout << "Received message from channel '" << channel 
                      << "': " << message << std::endl;
            
            // 根据频道处理不同的消息
            if (channel == "news") {
                std::cout << "Processing news: " << message << std::endl;
            } else if (channel == "sports") {
                std::cout << "Processing sports: " << message << std::endl;
            }
        });
        
        // 设置模式匹配消息回调
        subscriber.on_pmessage([](const std::string &pattern, 
                                const std::string &channel, 
                                const std::string &message) {
            std::cout << "Pattern '" << pattern << "' matched channel '" 
                      << channel << "' with message: " << message << std::endl;
        });
        
        // 订阅具体频道
        subscriber.subscribe("news");
        subscriber.subscribe("sports");
        
        // 订阅模式匹配频道
        subscriber.psubscribe("news.*");
        
        std::cout << "Subscribed to channels. Waiting for messages..." << std::endl;
        
        // 持续监听消息
        while (true) {
            try {
                subscriber.consume();
            } catch (const TimeoutError &e) {
                // 可以设置超时继续循环
                continue;
            }
        }
        
    } catch (const Error &e) {
        std::cerr << "Error: " << e.what() << std::endl;
        return 1;
    }
    
    return 0;
}